package com.parq.ie.google.customsearch;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.log4j.Logger;

public class CSRequest {

	private static Logger log = Logger.getLogger(CSRequest.class);
		
	public static synchronized String request(String appkey,String appid,String query) throws Exception {
//		if (true)
//			return null;
		StringBuilder request = new StringBuilder();
		request.append("https://www.googleapis.com/customsearch/v1?key=");
		request.append(appkey);
		request.append("&cx=");
		request.append(appid);
		request.append("&q=");
		request.append(query);
		request.append("&alt=atom");

		log.debug("Request " + request.toString());
		
		URL url = new URL(request.toString());
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("GET");
		connection.connect();
		int code=connection.getResponseCode();
		
		if (code!=200)
			throw new Exception("Response from Google is not OK. Response Code " + code);
		
		StringBuilder build=new StringBuilder();
		InputStream stream = connection.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(stream));
		String strLine;
		while ((strLine = br.readLine()) != null) {
			build.append(strLine);
		}

		return build.toString().trim();
	}
}
